package com.ruoyi.common.core.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zhangbin
 * @date 2023/7/7
 * @apiNote
 */
@Configuration
public class ThreadPoolConfig {

    // 核心线程池大小
    private static final int corePoolSize = 50;

    // 最大可创建的线程数
    private static final int maxPoolSize = 200;

    // 队列最大长度
    private static final int queueCapacity = 1000;

    // 线程池维护线程所允许的空闲时间
    private static final int keepAliveSeconds = 300;
    /**
     * 业务处理线程池
     *
     * @return 线程池
     */
    @Bean("businessTaskExecutor")
    public Executor businessTaskExecutor() {
        int cpu = Runtime.getRuntime().availableProcessors();
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setThreadNamePrefix("BusinessTaskExecutor-");
        threadPoolTaskExecutor.setCorePoolSize(cpu / 2);
        threadPoolTaskExecutor.setMaxPoolSize(cpu);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setKeepAliveSeconds(30);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        threadPoolTaskExecutor.initialize();
        return TtlExecutors.getTtlExecutor(threadPoolTaskExecutor);
    }
}
